package com.yfree.utils;

import android.os.Environment;

import com.yfree.YConfig;
import com.yfree.activities.YActivity;

import java.io.File;

/**
 * 本应用数据清除管理器
 */
public class YDataCleanManager {
    // 获取缓存大小（内部+外部）
    public static long getTotalCacheSize(YActivity context) {
        long cacheSize = 0;
        //cacheSize += getFolderSize(context.getCacheDir());
        cacheSize += getFolderSize(new File(context.getFilesDir(), "YCache"));
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            //cacheSize += getFolderSize(context.getExternalCacheDir());
            cacheSize += getFolderSize(new File(context.yBasePath + YConfig.FINALBITMAPCACHEDIR));
        }
        return cacheSize;
    }

    // 清理缓存（内部+外部）
    public static void clearAllCache(YActivity context) {
        //deleteDir(context.getCacheDir());
        deleteDir(new File(context.getFilesDir(), "YCache"));
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            //deleteDir(context.getExternalCacheDir());
            deleteDir(new File(context.yBasePath + YConfig.FINALBITMAPCACHEDIR));
        }
    }

    private static long getFolderSize(File file) {
        long size = 0;
        File[] fileList = file.listFiles();
        if (fileList == null) {
            return 0;
        }
        for (File aFileList : fileList) {
            // 如果下面还有文件
            if (aFileList.isDirectory()) {
                size = size + getFolderSize(aFileList);
            } else {
                size = size + aFileList.length();
            }
        }
        return size;
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (String aChildren : children) {
                if (!deleteDir(new File(dir, aChildren))) {
                    return false;
                }
            }
        }
        return dir.delete();
    }
}